package cn.lili.listener;

import cn.hutool.json.JSONUtil;
import cn.lili.cache.Cache;
import cn.lili.event.OrderStatusChangeEvent;
import cn.lili.event.TradeEvent;
import cn.lili.modules.order.cart.entity.dto.TradeDTO;
import cn.lili.modules.order.order.entity.dto.OrderMessage;
import cn.lili.routing.OrderRoutingKey;
import com.google.gson.Gson;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 订单消息
 *
 * @author paulG
 * @since 2020/12/9
 **/
@Component
@Slf4j
@RequiredArgsConstructor
public class OrderMessageListener {

    /**
     * 交易
     */
    private final List<TradeEvent> tradeEvent;

    /**
     * 订单状态
     */
    private final List<OrderStatusChangeEvent> orderStatusChangeEvents;

    /**
     * 缓存
     */
    private final Cache<Object> cache;

    /**
     * 订单创建
     *
     * @param key redis缓存key
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${lili.amqp.order}" + "_" + OrderRoutingKey.ORDER_CREATE),
            exchange = @Exchange(value = "${lili.amqp.order}"),
            key = OrderRoutingKey.ORDER_CREATE))
    public void orderCreate(String key) {

//        if(cache.get(key) == null) {
//            cache.remove(key);
//            return;
//        }

//        try {
//            new Gson().fromJson(cache.get(key).toString(), TradeDTO.class);
//        }catch(Exception e) {
//            return ;
//        }

//        System.out.println(cache.get(key).toString());
        TradeDTO tradeDTO = new Gson().fromJson(cache.get(key).toString(), TradeDTO.class);
        boolean result = true;
        for (TradeEvent event : tradeEvent) {
            try {
                event.tradeCreate(tradeDTO);
            } catch (Exception e) {
                log.error("交易{}入库,在{}业务中，状态修改事件执行异常",
                        tradeDTO.getSn(),
                        event.getClass().getName(),
                        e);
                result = false;
            }
        }
        //如所有步骤顺利完成
        if (Boolean.TRUE.equals(result)) {
            //清除记录信息的trade cache key
            cache.remove(key);
        }
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${lili.amqp.order}" + "_" + OrderRoutingKey.STATUS_CHANGE),
            exchange = @Exchange(value = "${lili.amqp.order}"),
            key = OrderRoutingKey.STATUS_CHANGE))
    public void orderChange(OrderMessage orderMessage) {

        //订单状态变更
        for (OrderStatusChangeEvent orderStatusChangeEvent : orderStatusChangeEvents) {
            try {
                log.info("订单状态变更事件：{}", JSONUtil.toJsonStr(orderMessage));
                orderStatusChangeEvent.orderChange(orderMessage);
            } catch (Exception e) {
                log.error("订单{},在{}业务中，状态修改事件执行异常",
                        orderMessage,
                        orderStatusChangeEvent.getClass().getName(),
                        e);
            }
        }
    }
}
